//
//  VanCommentViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/19.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "VanCommentViewController.h"
#import "CDZStarsControl.h"
#import "GoodsAddressModel.h"

static NSString *cellPath = @"CommentCell";
@interface VanCommentViewController ()<UITableViewDelegate,UITableViewDataSource,CDZStarsControlDelegate,UITextViewDelegate,UIScrollViewDelegate>
{
    UILabel *changeNumLab;
    UITextView *conView;
    
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)CDZStarsControl *starsControl;
@property (nonatomic, strong)NSArray *typeAry;
@property (nonatomic, strong)NSMutableArray *closeTypeAry;
@property (nonatomic, assign)NSInteger Score;
@property (nonatomic, strong)NSString *pladerStr;
@property (nonatomic, assign)BOOL isGx;

@end

@implementation VanCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _closeTypeAry = [NSMutableArray arrayWithCapacity:0];
    _pladerStr = @"说点什么、、、";
    _Score = 5;
    [self creatUI];
    [self requestComment];
}

- (void)creatUI
{
    self.navigationItem.title = @"货车评价";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-65*displaywidth) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    
    UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-55*displaywidth, SCREEN_WIDTH-30*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(soureBtnAction) Title:@"提交评论" Font:16.0];
    soureBtn.backgroundColor = RGB(255, 153, 0);
    [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    soureBtn.layer.cornerRadius = 5;
    soureBtn.layer.masksToBounds = YES;
    [self.view addSubview:soureBtn];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    if (indexPath.row == 0)
    {
        CDZStarsControl *starsAControl = [[CDZStarsControl alloc] initWithFrame:CGRectMake(75*displaywidth, 20*displaywidth, SCREEN_WIDTH-150*displaywidth , 45*displaywidth) stars:5 starSize:CGSizeMake(40*displaywidth, 40*displaywidth) noramlStarImage:[UIImage imageNamed:@"star_normal"] highlightedStarImage:[UIImage imageNamed:@"star01"]];
        starsAControl.delegate = self;
        starsAControl.allowFraction = NO;
        starsAControl.score = _Score;
        starsAControl.isEntlab = YES;
        [cell.contentView addSubview:starsAControl];
        _starsControl = starsAControl;
        UILabel *numLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 80*displaywidth, SCREEN_WIDTH-30*displaywidth, 35*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@"评 %ld 分",_Score] Color:RGB(204, 204, 204)];
        numLab.textAlignment = NSTextAlignmentCenter;
        NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"评 %ld 分",_Score]];
        NSRange titleRange = [[title string]rangeOfString:[NSString stringWithFormat:@" %ld ",_Score]];
        [title addAttribute:NSForegroundColorAttributeName value:RGB(255, 204, 0) range:titleRange];
        [title addAttribute:NSFontAttributeName value:NormalFontWithSize(18.0+fontScale) range:titleRange];
        numLab.attributedText = title;
        changeNumLab = numLab;
        [cell.contentView addSubview:numLab];
        
    }
    else if (indexPath.row == 1)
    {
        UIView *lineBview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10*displaywidth)];
        lineBview.backgroundColor = BacksColor;
        [cell.contentView addSubview:lineBview];
        if (_typeAry.count > 0)
        {
            CGFloat h2 = 25*displaywidth;
            CGFloat w2 = 0;
            CGFloat width = SCREEN_WIDTH;
            for (int i = 0; i < _typeAry.count; i++)
            {
                GoodsAddressModel *sizeModel = _typeAry[i];
                NSString *typename = [NSString stringWithFormat:@"%@(%@)",sizeModel.name,sizeModel.count];
                UIButton *tasteBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth+i*75*displaywidth, h2, 60*displaywidth, 25*displaywidth) ImageName:nil Target:self Action:@selector(tasteBtnAction:) Title:typename Font:12.0];
                tasteBtn.tag = 500+i;
                NSDictionary *attributes = @{NSFontAttributeName:NormalFontWithSize(12.0+fontScale)};
                CGFloat length = [typename boundingRectWithSize:CGSizeMake(2000, 25*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
                if (length > width-45*displaywidth)
                {
                    length = width-45*displaywidth;
                }
                tasteBtn.frame = CGRectMake(15*displaywidth + w2, h2, length + 15*displaywidth , 25*displaywidth);
                if(15*displaywidth + w2 + length + 15*displaywidth > width){
                    w2 = 0; //换行时将w置为0
                    h2 = h2 + tasteBtn.frame.size.height + 20*displaywidth;//距离父视图也变化
                    tasteBtn.frame = CGRectMake(15*displaywidth + w2, h2, length + 15*displaywidth, 25*displaywidth);//重设button的frame
                }
                w2 = tasteBtn.frame.size.width + tasteBtn.frame.origin.x+10*displaywidth;
                
                UIColor *bordercolor2 = BacksColor;
                UIColor *titcolor2 = BlaTitColor;
                if ([_closeTypeAry containsObject:s_str(sizeModel.name)])
                {
                    bordercolor2 = RGB(255, 204, 0);
                    titcolor2 = [UIColor whiteColor];
                }
                [tasteBtn setTitleColor:titcolor2 forState:UIControlStateNormal];
                tasteBtn.layer.cornerRadius = 12.5*displaywidth;
                tasteBtn.layer.masksToBounds = YES;
                tasteBtn.backgroundColor = bordercolor2;
                [cell.contentView addSubview:tasteBtn];
                
            }
            h2+=40*displaywidth;
            UIView *lineCview = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, h2-1, SCREEN_WIDTH-30*displaywidth, 1)];
            lineCview.backgroundColor = LinesColor;
            [cell.contentView addSubview:lineCview];
        }
        
    }
    else
    {
        UITextView *contentAView = [[UITextView alloc] initWithFrame:CGRectMake(15*displaywidth, 20*displaywidth, SCREEN_WIDTH-30*displaywidth, 150*displaywidth)];
        contentAView.delegate = self;
        contentAView.text = _pladerStr;
        contentAView.textColor = RGB(179, 179, 179);
        if (![_pladerStr isEqualToString:@"说点什么、、、"])
        {
            contentAView.textColor = BlaTitColor;
        }
        contentAView.backgroundColor = BacksColor;
        contentAView.layer.cornerRadius = 10;
        contentAView.layer.masksToBounds = YES;
        [cell.contentView addSubview:contentAView];
        conView = contentAView;
        NSString *imgStr = @"gouxuan1";
        if (_isGx)
        {
            imgStr = @"gouxuan2";
        }
        UIButton *gouXuan = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, 190*displaywidth, 150*displaywidth, 20*displaywidth) ImageName:imgStr Target:self Action:@selector(gouxuanAction:) Title:@" 是否匿名" Font:12.0];
        [gouXuan setTitleColor:ThemeColor forState:UIControlStateNormal];
        gouXuan.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        gouXuan.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [cell.contentView addSubview:gouXuan];
        
    }
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        return 125*displaywidth;
    }
    else if (indexPath.row == 1)
    {
        CGFloat h2 = 10*displaywidth;
        CGFloat w2 = 0;
        CGFloat width = SCREEN_WIDTH;
        if (_typeAry.count > 0)
        {
            h2 = 25*displaywidth;
            for (int i = 0; i < _typeAry.count; i++)
            {
                GoodsAddressModel *sizeModel = _typeAry[i];
                NSString *typename = [NSString stringWithFormat:@"%@(%@)",sizeModel.name,sizeModel.count];
                NSDictionary *attributes = @{NSFontAttributeName:NormalFontWithSize(12.0+fontScale)};
                CGFloat length = [typename boundingRectWithSize:CGSizeMake(2000, 25*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
                if (length > width-45*displaywidth)
                {
                    length = width-45*displaywidth;
                }
                if(15*displaywidth + w2 + length + 15*displaywidth > width){
                    w2 = 0; //换行时将w置为0
                    h2 = h2 + 25 + 20*displaywidth;//距离父视图也变化
                }
                w2 = length + 15*displaywidth + 15*displaywidth + w2;
            }
            h2+=40*displaywidth;
        }
        
        return h2;
    }
    return 230*displaywidth;
}

- (void)starsControl:(CDZStarsControl *)starsControl didChangeScore:(CGFloat)score
{
    NSInteger num = score/1;
    _Score = num;
    //    _starsControl.score = num*1.0f;
    NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"评 %ld 分",_Score]];
    NSRange titleRange = [[title string]rangeOfString:[NSString stringWithFormat:@" %ld ",_Score]];
    [title addAttribute:NSForegroundColorAttributeName value:RGB(255, 204, 0) range:titleRange];
    [title addAttribute:NSFontAttributeName value:NormalFontWithSize(18.0+fontScale) range:titleRange];
    changeNumLab.attributedText = title;
}

- (void)tasteBtnAction:(UIButton *)btn
{
    NSInteger index = btn.tag-500;
    GoodsAddressModel *model = _typeAry[index];
    [_closeTypeAry removeAllObjects];
    [_closeTypeAry addObject:s_str(model.name)];
    [_tableview reloadData];
}

- (void)gouxuanAction:(UIButton *)btn
{
    _isGx = !_isGx;
    NSString *imgStr = @"gouxuan1";
    if (_isGx)
    {
        imgStr = @"gouxuan2";
    }
    [btn setImage:IMAGE(imgStr) forState:UIControlStateNormal];
    [btn setTitle:@"是否匿名" forState:UIControlStateNormal];
}

- (void)soureBtnAction
{
    if (_closeTypeAry.count == 0)
    {
        [LTools showMBProgressWithText:@"请选择评价类别" addToView:self.view];
        return;
    }
    WEAKSELF;
    NSString *contentStr = conView.text;
    if ([contentStr isEqualToString:@"说点什么、、、"])
    {
        contentStr = @"";
    }
    NSString *isAn = @"0";
    if (_isGx)
    {
        isAn = @"1";
    }
    NSDictionary *dic = @{@"joinId":_carID,
                          @"type":@"3",
                          @"rate":s_Integer(_Score),
                          @"label":_closeTypeAry[0],
                          @"content":contentStr,
                          @"isAnonymous":isAn
                          };
    [HYBaseHandler requestWithTheFormUrl:SERVER_commentSave Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [LTools showMBProgressWithText:@"评论成功" addToView:sharedDelegate.window];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)requestComment
{
    WEAKSELF;
    NSDictionary *dic = @{@"joinId":_carID,
                          @"type":@"2",
                          @"size":@"9999"
                          };
    [HYBaseHandler requestWithTheFormUrl:SERVER_commentType Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _typeAry = [GoodsAddressModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

//开始编辑
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    textView.textColor = BlaTitColor;
    if ([textView.text isEqualToString:@"说点什么、、、"])
    {
        textView.text= @"";
    }
    _tableview.frame = CGRectMake(0, -120, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-65*displaywidth);
}



//结束编辑
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""])
    {
        textView.text = @"说点什么、、、";
        textView.textColor = RGB(179, 179, 179);
    }
    _pladerStr = textView.text;
    _tableview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-65*displaywidth);
}

- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    return indexPath;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self.view endEditing:YES];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
